/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2020-12-29 08:44:29
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-22 14:15:54
 * @Description: 系统用户 模型
 */

import { Application } from "egg";
import { Model } from "sequelize";
import { modelCommonField } from "../../utils";
export interface sys_user extends Model {
  id: number;
  user_name: string;
  user_uuid: string;
  password: string;
  real_name: string;
  phone_num: string;
  email: string;
  role_ids: string;
  is_use: boolean;
  /** 头像 */
  avatar: string;
  /** 创建者id */
  create_user_id: number;
  /** 修改者id */
  edit_user_id: number;
}

/**
 *sys_user 系统用户模型
 *
 * @param {*} app
 * @return {*}
 */
export default (app: Application) => {
  const { STRING, UUID, BOOLEAN } = app.Sequelize;

  const User = app.model.define<sys_user>(
    app.config.dbModel_prefix + "sys_user",
    {
      // 注意所有模型都有自动添加的id字段。因此无需手动添加主键。
      // id: {
      //     type: INTEGER(10),
      //     primaryKey: true,
      //     autoIncrement: true,
      //     comment: "用户自动ID"
      // },
      user_uuid: {
        type: UUID,
        defaultValue: app.Sequelize.UUIDV4, // 或 Sequelize.UUIDV1
        comment: "用户UUID",
      },
      user_name: {
        type: STRING(50),
        comment: "用户登录名，唯一",
        allowNull: false,
        unique: true, //唯一字段
      },
      password: {
        type: STRING(64),
        comment: "密码",
        allowNull: false,
      },
      real_name: {
        type: STRING(30),
        comment: "用户真实姓名",
      },
      phone_num: {
        type: STRING(30),
        comment: "手机号",
      },
      email: {
        type: STRING(50),
        comment: "邮箱",
      },

      role_ids: {
        type: STRING(300),
        comment: "角色ID集合",
      },
      is_use: {
        type: BOOLEAN,
        comment: "是否可用",
      },
      avatar: {
        field: "avatar",
        type: STRING(500),
        comment: "用户头像",
      },
      ...modelCommonField,
    },
    {
      freezeTableName: true, //冻结表名，因sequelize会自动复数 define定义的表名。冻结之后既直接使用define作为表名。
      timestamps: true, //使用自动的时间戳字段。
      paranoid: true, //使用偏执表，即删除一行数据时，只标记某个字段，而不是物理删除。
    }
  );

  // 非生产 临时创建用户测试
  if (app.config.env !== "prod") {
    User.findOrCreate({
      defaults: {
        user_name: "editor",
        password: "96e79218965eb72c92a549dd5a330112",
        real_name: "editor",
        is_use: true,
        role_ids:1
      },
      where: {
        user_name: "editor",
      },
    });
    User.findOrCreate({
      defaults: {
        user_name: "admin",
        password: "96e79218965eb72c92a549dd5a330112",
        real_name: "admin",
        is_use: true,
        role_ids:1
      },
      where: {
        user_name: "admin",
      },
    });
  }

  return User;
};
